/* SVN FILE: $Id: script.js 76 2011-12-28 15:15:03Z lga $ */

String.prototype.hashCode = function () {
	'use strict';
	var i, hash = 0, chr;
	if (this.length === 0) { return hash; }
	for (i = 0; i < this.length; i++) {
		chr = this.charCodeAt(i);
		hash = ((hash << 5) - hash) + chr;
		hash = hash & hash; // Convert to 32bit integer
	}
	return hash;
};

var show = {
    show : function () {
        return this.setStyle('display', 'block');
    }
}

var hide = {
    hide : function () {
        return this.setStyle('display', 'none');
    }
}

var parent = {
    parent : function () {
        return x$(this[0].parentNode);
    }
};

var children = {
    children : function () {
        return this.find('*');
    }
};

var serializeForm = function (f) {
	'use strict';
	var idx, el, els, retVal = '';
	els = f.getElementsByTagName('*');
	for (idx = 0; idx < els.length; idx++) {
		el = els[idx];
		if (!el.disabled && el.name && el.name.length > 0) {
			switch (el.tagName.toLowerCase()) {
			case 'input':
				switch (el.type) {
				case 'checkbox':
				case 'radio':
					if (el.checked) {
						if (retVal.length > 0) {
							retVal	+= '&';
						}
						retVal += el.name + '=' + encodeURIComponent(el.value);
					}
					break;
				case 'hidden':
				case 'password':
				case 'text':
					if (retVal.length > 0) {
						retVal += '&';
					}
					retVal += el.name + '=' + encodeURIComponent(el.value);
					break;
				}
				break;
			case 'select':
			case 'textarea':
				if (retVal.length > 0) {
					retVal	+= '&';
				}
				retVal += el.name + '=' + encodeURIComponent(el.value);
				break;
			}
		}
	}
	return retVal;
};
var serialize = function (obj, prefix, encode) {
	'use strict';
	var p, k, v, str = [];
	for (p in obj) {
		if (obj.hasOwnProperty(p)) {
			k = (prefix) ? prefix + "[" + p + "]" : p;
			v = obj[p];
			str.push((typeof v === "object") ? serialize(v, k) : ((encode) ? encodeURIComponent(k) : k) + "=" + ((encode) ? encodeURIComponent(v) : v));
		}
	}
	return str.join("&");
};

var wxMobile = {
	storageKey: 'GEOPOSITION',
	position: {
		"denied": null,
		"unavailable": null,
		"lat": null,
		"lng": null,
		"city_id": null,
		"city": null,
		"county_id": null,
		"area_id": null,
		"user": null,
		"modified": null
	},
	initialize: function (pos) {
		'use strict';
		if (this.cookieEnabled()) {
			if (typeof (pos) === 'undefined' || pos === null) {
				this.set_location();
			} else {
				this.position = pos;
			}
			xui.extend(show);
			xui.extend(hide);
			xui.extend(parent);
			xui.extend(children);
			this.search();
			this.filters();
			this.toggleWeatherFiler();
			this.toggleInfoFiler();
			this.toggleAerodromeInfo();
			this.toggleAerodromeWeather();
			this.initRunwayInfo();
			// this.tabs();
			// this.updateFV();
			// this.manual_location();
			// this.move();
			this.flickrInit();
			// this.photocredits();
		} else {
			alert("Cookies must be enabled for this site to work.");
		}
	},
	cookieEnabled: function () {
		'use strict';
		var enabled = (navigator.cookieEnabled) ? true : false;
		if (typeof (navigator.cookieEnabled) === "undefined" && enabled === false) {
			document.cookie = "myTestCookie";
			enabled = (document.cookie.indexOf("myTestCookie") !== -1) ? true : false;
		}
		return enabled;
	},
	flickrInit: function () {
		'use strict';
		if (x$('.flickr_badge_image')) {
			var flickr_image = x$('.flickr_badge_image a');
			//flickr_image.css('margin-left', -(flickr_image.width/2) + "px");
			//flickr_image.css('margin-top', -(flickr_image.height/2) + "px");
			flickr_image.href = "#";
			//flickr_image.fadeIn('fast');
		}
	},
	search: function () {
		'use strict';
		x$('#search_trigger').click(function () {
			console.log(x$('#search_trigger').html()[0]);
			if (x$('#search_trigger').html()[0].indexOf('icon-search') > -1) {
				x$('section[role="search"]').tween({marginTop: '0', opacity: '50'});
				x$('#search_trigger').html("<i class='icon-cancel-circle'></i>");
			} else {
				x$('section[role="search"]').tween({marginTop: '-62px'});
				x$('#search_trigger').html("<i class='icon-search-1'></i>");
			}
			return false;
		});
		x$('[role=search] [type=search]').on('focus', function () {
			if (this.value === this.defaultValue) {
				this.value = '';
			}
			if (this.value !== this.defaultValue) {
				this.select();
			}
		});
		x$('[role=search] [type=search]').on('blur', function () {
			if (this.value === '') {
				this.value = this.defaultValue;
			}
		});
	},

	fetchSearchStorage: function () {
		'use strict';
		if (typeof (localStorage) === 'undefined') {
			return;
		} else {
			var searchStorage = localStorage['search'];
			return (searchStorage && searchStorage !== null) ? JSON.parse(searchStorage) : null;
		}
	},
	saveSearch: function (keywords) {
		'use strict';
		if (typeof (localStorage) === 'undefined') {
			return;
		} else {
			// Search string
			var strSearch = Array(keywords, 1);
			var isNew = true;
			// Get search storage parsed as JSON			
			var searchStorage = wxMobile.fetchSearchStorage();
			// Checking if the storage is empty
			searchStorage = (!searchStorage || searchStorage === null) ? new Array() : searchStorage;
			for (var i = searchStorage.length - 1; i >= 0; i--) {
				// Existing search, update the count
				if (searchStorage[i][0] === strSearch[0]) {
					searchStorage[i][1]++; 
					isNew = false;
				}
			};
			// New search
			if (isNew) searchStorage.push(strSearch);	
			localStorage['search'] = JSON.stringify(searchStorage, false, false);
		}
	},
	filters: function () {
		'use strict';
		if (typeof (localStorage) === 'undefined') {
			return;
		} else {
			var filter_icon = x$('.filter_icon');
			if (!localStorage['filter']) localStorage['filter'] = 'icon-globe';
			(localStorage['filter'] == "icon-cloud") ? wxMobile.toggleWeatherFiler(true) : wxMobile.toggleInfoFiler(true);
			filter_icon.addClass(localStorage['filter']);
			filter_icon.click(function () {
				wxMobile.toggleWeatherFiler();
				wxMobile.toggleInfoFiler();
				x$(this).toggleClass('icon-globe').toggleClass('icon-cloud');
				localStorage['filter'] = x$(this).hasClass('icon-globe') ? 'icon-globe' : 'icon-cloud';
			});
		}
	},
	toggleWeatherFiler: function (init) {
		(init) ? 
			x$('.aerodrome_basic_weather, .weather_toggles').addClass('show') : 
			x$('.aerodrome_basic_weather, .weather_toggles').toggleClass('show');
		if (!init) x$('.map_toggle').fire('click');
	},
	toggleInfoFiler: function (init) {
		(init) ? 
			x$('.aerodrome_extras, .main_info_toggles').addClass('show') : 
			x$('.aerodrome_extras, .main_info_toggles').toggleClass('show');
		if (!init) x$('.map_toggle').fire('click');
	},
	toggleAerodromeInfo: function (init) {
		x$('.runway_toggle').on('click', function () {
			var info_container = x$(this).parent().parent();
			info_container.find('.toggle').each(function () {
				if (!x$(this).hasClass('aerodrome_runways')) x$(this).tween({opacity: '0'});
			});
			info_container.find('.aerodrome_runways').tween({opacity: '100'});
			info_container.find('.main_info_toggles > span').each(function(){x$(this).removeClass('active_toggle');});
			info_container.find('.runway_toggle').addClass('active_toggle');
		});
		x$('.comm_toggle').on('click', function () {
			var info_container = x$(this).parent().parent();
			info_container.find('.toggle').each(function () {
				if (!x$(this).hasClass('aerodrome_comm')) x$(this).tween({opacity: '0'});
			});
			info_container.find('.aerodrome_comm').tween({opacity: '100'});
			info_container.find('.main_info_toggles > span').each(function(){x$(this).removeClass('active_toggle');});
			info_container.find('.comm_toggle').addClass('active_toggle');			
		});
		x$('.map_toggle').on('click', function () {
			var info_container = x$(this).parent().parent();
			info_container.find('.toggle').each(function () {
				if (!x$(this).hasClass('openMap')) x$(this).tween({opacity: '0'});
			});
			info_container.find('.openMap').tween({opacity: '100'});
			info_container.find('.main_info_toggles > span').each(function(){x$(this).removeClass('active_toggle');});
			info_container.find('.weather_toggles > span').each(function(){x$(this).removeClass('active_toggle');});
			info_container.find('.map_toggle').addClass('active_toggle');				
		});
	},
	toggleAerodromeWeather: function (init) {
		x$('.metar_toggle').on('click', function () {
			var info_container = x$(this).parent().parent();
			info_container.find('.toggle').each(function () {
				if (!x$(this).hasClass('aerodrome_metars')) x$(this).tween({opacity: '0'});
			});
			info_container.find('.aerodrome_metars').tween({opacity: '100'});
			info_container.find('.weather_toggles > span').each(function(){x$(this).removeClass('active_toggle');});
			info_container.find('.metar_toggle').addClass('active_toggle');					
		});
		x$('.taf_toggle').on('click', function () {
			var info_container = x$(this).parent().parent();
			info_container.find('.toggle').each(function () {
				if (!x$(this).hasClass('aerodrome_tafs')) x$(this).tween({opacity: '0'});
			});
			info_container.find('.aerodrome_tafs').tween({opacity: '100'});
			info_container.find('.weather_toggles > span').each(function(){x$(this).removeClass('active_toggle');});
			info_container.find('.taf_toggle').addClass('active_toggle');								
		});

	},	
	requestADDS: function (stations, type) {

		x$('.aerodromes').xhr("/views/adds_request.php?stations=" + stations + "&type=" + type, {
		   async: true,
		   method: 'get',
		   data: 'xml',
		   callback: function() {

				var xmlString = this.responseText
			  	, parser = new DOMParser()
			  	, doc = parser.parseFromString(xmlString, "text/xml");

				wxMobile.parseADDS(x$(doc), type, stations);
		   },
		   headers: {
		       'Mobile':'true',
		       'Content-Type':'text/xml;charset=UTF-8'
		   }
		});

	},
	parseADDS: function (data, type, queried_stations) {

		// Building up a list of requested stations
		var wx_stations = queried_stations.split(" ");
		var stations = new Object();
		for (var i = wx_stations.length - 1; i >= 0; i--) {
			// Setting the markers for latest wx data
			var stn_id = wx_stations[i];
			stations[stn_id] = {
				isWindSet:false,
				isPressureSet:false,
				isTempSet:false,
				isVisSet:false
			};
		};

		if (type == "metars") {

			data.find('METAR').each(function(){

				// Station id
				var station_id = x$(this).find('station_id')[0].textContent;

				// Raw metar
 				var metar = x$(this).find('raw_text')[0].textContent;

 				// metar or speci
 				var reportType = x$(this).find('metar_type')[0].textContent;

 				// Obtaining latest conditions, if current metar/speci is missing any data get it from the previous report
 				var latest_conditions = {};

				// Latest wind
				if (!stations[station_id].isWindSet) {
					var wind_dir_degrees = x$(this).find('wind_dir_degrees')[0];
					var wind_speed_kt = x$(this).find('wind_speed_kt')[0];
					var wind_gust_kt = x$(this).find('wind_gust_kt')[0];
 					latest_conditions.wind_dir_degrees = (wind_dir_degrees) ? ('00' + wind_dir_degrees.textContent).slice(-3) : null;
 					latest_conditions.wind_speed_kt = (wind_speed_kt) ? wind_speed_kt.textContent : null;
 					latest_conditions.wind_gust_kt = (wind_gust_kt) ? "</strong>G<strong>" + wind_gust_kt.textContent : "";
					if (latest_conditions.wind_dir_degrees != null && latest_conditions.wind_speed_kt != null) {
						var windString = (latest_conditions.wind_speed_kt == 0) ? "calm" : "<strong>" +	latest_conditions.wind_dir_degrees + "</strong> @ <strong>" + latest_conditions.wind_speed_kt + latest_conditions.wind_gust_kt + "</strong>kt";
	 					x$("." + station_id).find('.latest_conditions_wind').html(windString);
	 					stations[station_id].isWindSet = true;							
					}
				}


				// Latest temperature
				if (!stations[station_id].isTempSet) {
					var temp_c = x$(this).find('temp_c')[0];
					var dewpoint_c = x$(this).find('dewpoint_c')[0];
					latest_conditions.temp_c = (temp_c) ? temp_c.textContent : null;
 					latest_conditions.dewpoint_c = (dewpoint_c) ? dewpoint_c.textContent : null;
					if (latest_conditions.temp_c != null) {
						var tempString = "<strong>" + latest_conditions.temp_c + "</strong>&deg;";
	 					x$("." + station_id).find('.latest_conditions_temperature').html(tempString);
	 					stations[station_id].isTempSet = true;							
					}
				}

				// Latest pressure
				if (!stations[station_id].isPressureSet) {
					var sea_level_pressure_mb = x$(this).find('sea_level_pressure_mb')[0];
					var three_hr_pressure_tendency_mb = x$(this).find('three_hr_pressure_tendency_mb')[0];
 					latest_conditions.sea_level_pressure_mb = (sea_level_pressure_mb) ? sea_level_pressure_mb.textContent : null;
 					latest_conditions.three_hr_pressure_tendency_mb = (three_hr_pressure_tendency_mb) ? three_hr_pressure_tendency_mb.textContent : null;
					if (latest_conditions.sea_level_pressure_mb == null) {
 						// Find pressure embeded in the raw metar
						var metar_raw = metar.split(" ");
						for (var i = metar_raw.length - 1; i >= 0; i--) {
							// looking for "Q1013" format
							if (metar_raw[i].length == 5 && metar_raw[i].charAt(0) == "Q") {
								latest_conditions.sea_level_pressure_mb = metar_raw[i].slice(-4);
							}
						};
 					} 
 					if (latest_conditions.sea_level_pressure_mb != null) {
 						var presString = "<strong>" + latest_conditions.sea_level_pressure_mb + "</strong>mb";
 						// Pressure tendency
 						if (latest_conditions.three_hr_pressure_tendency_mb != null) {
 							var presTendency = "";
 							presTendency = (latest_conditions.three_hr_pressure_tendency_mb < 0) ? "&darr;" : "&uarr;"
 							presString = presString + " (" + presTendency + " " + latest_conditions.three_hr_pressure_tendency_mb + ")";
 						}
						x$("." + station_id).find('.latest_conditions_pressure').html(presString);
						stations[station_id].isPressureSet = true;
 					}
				}

				// Latest visibility
				if (!stations[station_id].isVisSet) {
					var visibility_statute_mi = x$(this).find('visibility_statute_mi')[0];
 					latest_conditions.visibility_statute_mi = (visibility_statute_mi) ? visibility_statute_mi.textContent : null;
 					if (latest_conditions.visibility_statute_mi != null) {
 						x$("." + station_id).find('.latest_conditions_visibility').html("<strong>" + latest_conditions.visibility_statute_mi + "</strong>sm");
 						stations[station_id].isVisSet = true;
 					}
				}
				var reportString = (reportType == 'METAR') ? "<p class='metar'>" + metar + "</p>" : "<p class='speci'>" + metar + "</p>";
 				x$("." + station_id).find('.aerodrome_metars').bottom(reportString);
			});

		} else if (type == "tafs") {

			data.find('TAF').each(function(){

				// Station id
				var station_id = x$(this).find('station_id')[0].textContent;

				// Raw taf
 				var taf = x$(this).find('raw_text')[0].textContent;

				var reportString = "<p class='taf'>" + taf + "</p>";
 				x$("." + station_id).find('.aerodrome_tafs').bottom(reportString);

			});


		}
	},
	initRunwayInfo: function () {
	 // Runway show more info
	 	x$('.runway_container').on('click', function () {
	 		var this_more_info_container = x$(this).find('.runway_more_info');
	 		if (!this_more_info_container.hasClass('visible_runway')) {
	 			x$('.runway_more_info').hide().removeClass('visible_runway');
	 			this_more_info_container.addClass('visible_runway').show();
	 		} else {
	 			x$('.runway_more_info').hide().removeClass('visible_runway');
	 		}
	 	});
	},
	/*move: function () {
		'use strict';
		if (typeof (localStorage) === 'undefined') {
			x$('a.up, a.down').addClass('hidden');
			return;
		}
		if (x$('a.up').length > 0) {
			x$('a.up').click(function (e) {
				e.preventDefault();
				var uid = x$(this).attr('data-favorite');
				if (uid.length > 0) {
					myFavorites.up(uid[0]);
					wxMobile.fetchFV('favorites');
				} else {
					myVisits.up(x$(this).attr('data-visit')[0]);
					wxMobile.fetchFV('visits');
				}
			});
		}
		if (x$('a.down').length > 0) {
			x$('a.down').click(function (e) {
				e.preventDefault();
				var uid = x$(this).attr('data-favorite');
				if (uid.length > 0) {
					myFavorites.down(uid[0]);
					wxMobile.fetchFV('favorites');
				} else {
					myVisits.down(x$(this).attr('data-visit')[0]);
					wxMobile.fetchFV('visits');
				}
			});
		}
	},*/
	/*fetchFV: function (type) {
		'use strict';
		var uids, url;
		if (type === 'visits') {
			url = "/visits/fetch";
			uids = myVisits.getUids();
		} else {
			url = "/favorites/fetch";
			uids = myFavorites.getUids();
		}
		x$().xhr(url, {
			method: "post",
			data: serialize({'data': {'uids': uids}}),
			callback: function () {
				x$("#resultset").html(this.responseText);
				wxMobile.move();
				wxMobile.updateFV();
			}
		});
	},*/
	/*tabs: function () {
		'use strict';
		if (x$('#tabs')) {
			x$('#tabs a').click(function () {
				x$('#tabs .active').removeClass('active');
				x$(this.parentElement).toggleClass('active');
				var id = x$(this).attr('id');
				x$('#tab_content li').each(function (element, index, xui) {
					if (x$(this).hasClass(id)) {
						x$(this).addClass('active');
					} else {
						x$(this).removeClass('active');
					}
				});
				return false;
			});
		}
	},*/
	/*photocredits: function () {
		'use strict';
		var i, credit, imgs = x$('img');
		if (imgs.length > 0) {
			for (i = 0; i < imgs.length; i++) {
				if (x$(imgs[i]).attr('data-photo-credit').length > 0) {
					x$(imgs[i]).after('<span class="photo-credit">' + x$(imgs[i]).attr('data-photo-credit')[0] + '</span>');
				}
			}
		}
	},*/
	/*updateFV: function () {
		'use strict';
		if (typeof (localStorage) === 'undefined') {
			x$('a.favorites, a.visit').addClass('hidden');
			return;
		}
		x$('a.favorites[data-favorite]').each(function () {
			var uid = x$(this).attr('data-favorite')[0];
			if (myFavorites.hasUid(uid)) {
				x$(this).addClass('checked');
				x$(this).find('span').html("Remove from Favorites");
			} else {
				x$(this).removeClass('checked');
				x$(this).find('span').html("Add to Favorites");
			}
			x$(this).click(function (e) {
				e.preventDefault();
				var method = "removeClass", label = "Add to Favorites";
				if (myFavorites.toggle(uid)) {
					method = "addClass";
					label = "Remove from Favorites";
				}
				x$('a[data-favorite="' + uid + '"]').each(function () {
					x$(this)[method]('checked');
					x$(this).find('span').html(label);
				});
			});
		});
		x$('a.visit[data-visit]').each(function () {
			var uid = x$(this).attr('data-visit')[0];
			if (myVisits.hasUid(uid)) {
				x$(this).addClass('checked');
				x$(this).find('span').html("Remove from Visits");
			} else {
				x$(this).removeClass('checked');
				x$(this).find('span').html("Add to Visits");
			}
			x$(this).click(function (e) {
				e.preventDefault();
				var method = "removeClass", label = "Add to Visits";
				if (myVisits.toggle(uid)) {
					method = "addClass";
					label = "Remove from Visits";
				}
				x$('a[data-visit="' + uid + '"]').each(function () {
					x$(this)[method]('checked');
					x$(this).find('span').html(label);
				});
			});
		});
	},*/
	set_location: function () {
		'use strict';
		if (x$('#change_location').length === 1) {
			return;
		}
		var that = this, refresh = false;
		if (this.position.denied !== 1 && this.position.unavailable !== 1) {
			if (geo_position_js.init()) {
				geo_position_js.getCurrentPosition(
					function (p) {
						that.geo_success(p);
					},
					function (error) {
						that.geo_error(error);
					},
					{maximumAge: 75000, enableHighAccuracy: false, timeout: 5000}
				);
			}
		}
	},
	geo_success: function (p) {
		'use strict';
		this.position.lat = p.coords.latitude.toFixed(4);
		this.position.lng = p.coords.longitude.toFixed(4);
		this.position.denied = 0;
		this.position.unavailable = 0;
		this.position.city_id = null;
		this.position.city = null;
		this.position.county_id = null;
		this.position.area_id = null;
		this.position.user = 0;
		if (localStorage) {
			localStorage.setObject(this.storageKey, this.position);
		}
		this.set_session();
	},
	geo_error: function (error) {
		'use strict';
		switch (error.code) {
		case error.PERMISSION_DENIED:
			alert('You have decided to not use GPS to set your location. You can set a location at the bottom of the page.');
			this.position.denied = 1;
			break;
		case error.POSITION_UNAVAILABLE:
		case error.TIMEOUT:
			alert('We are unable to establish your position so we\'ve selected a location for you. You can change your location at the bottom of the page.');
			this.position.unavailable = 1;
			break;
		default:
			return;
		}
		this.set_session();
	},
	set_session: function () {
		'use strict';
		if (this.cookieEnabled()) {
			x$().xhr("/locations/setlocation.json", {
				method: "post",
				data: serialize({'data': {'Position': this.position}}),
				callback: function () {
					var obj = eval("(" + this.responseText + ")");
					if (obj.denied === "1" || obj.unavailable === "1") {
						window.location = "/";
					} else {
						window.location.reload(true);
					}
				}
			});
		}
	},
	manual_location: function () {
		'use strict';
		if (x$('#change_location').length === 1) {
			x$('#CountyAreaId').on('change', function (e) {
				x$('#CityId')[0].selectedIndex = 0;
				x$('#change_location')[0].submit();
			});
			x$('#CityId').on('change', function (e) {
				x$('#change_location')[0].submit();
			});
		}
	}
};
x$.ready(function () {
	'use strict';
	if (window.location.pathname === '/') {
		window.setTimeout(function () {
			var parameter, bubble = new google.bookmarkbubble.Bubble();
			parameter = 'bmb=1';
			bubble.hasHashParameter = function () {
				return window.location.hash.indexOf(parameter) !== -1;
			};
			bubble.setHashParameter = function () {
				if (!this.hasHashParameter()) {
					window.location.hash += parameter;
				}
			};
			bubble.getViewportHeight = function () {
				return window.innerHeight;
			};
			bubble.getViewportScrollY = function () {
				return window.pageYOffset;
			};
			bubble.registerScrollHandler = function (handler) {
				window.addEventListener('scroll', handler, false);
			};
			bubble.deregisterScrollHandler = function (handler) {
				window.removeEventListener('scroll', handler, false);
			};
			bubble.showIfAllowed();
		}, 3000);
	}


});